package com.example.musicplayer.commonUtils;

import android.content.Context;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.musicplayer.MusicPlayerApplication;
import com.example.musicplayer.R;

import java.util.List;

//MainActivity页面的tab下划线管理类
public class TabUnderLineUtil {
    //每个tab的内容与组件的内部padding
    private int mContentPadding;
    //tab列表
    private List<TextView> mTextViews;
    //下划线组件
    private ImageView mImageViewLine;
    //下划线布局对象
    private LinearLayout.LayoutParams mLayoutParamsLine;

    public TabUnderLineUtil(ImageView imageViewLine, List<TextView> textViews, int position) {
        Context context = MusicPlayerApplication.getInstance();
        mContentPadding = (int) context.getResources().getDimension(R.dimen.activity_main_top_bar_tab_content_padding);
        mTextViews = textViews;
        mImageViewLine = imageViewLine;
        mLayoutParamsLine = (LinearLayout.LayoutParams) mImageViewLine.getLayoutParams();
        //初始化下划线的位置
        int lineWidth = getLineWidth(position);
        int offset = getOffSet(0);
        mLayoutParamsLine.width = lineWidth;
        mLayoutParamsLine.leftMargin = offset;
        mImageViewLine.setLayoutParams(mLayoutParamsLine);
    }

    //更新下划线的位置
    public void updateUnderLine(int position, float positionOffset) {
        mLayoutParamsLine = (LinearLayout.LayoutParams) mImageViewLine.getLayoutParams();
        if (mLayoutParamsLine != null && positionOffset != 0.0f) {
            int offset1 = getOffSet(position);
            int offset2 = getOffSet(position + 1);
            int margin = offset1 + (int) ((offset2 - offset1) * positionOffset);
            int width = getLineWidth(position) +
                    (int) ((getLineWidth(position + 1) - getLineWidth(position)) * positionOffset);
            mLayoutParamsLine.leftMargin = margin;
            mLayoutParamsLine.width = width;
            mImageViewLine.setLayoutParams(mLayoutParamsLine);
        }
    }

    //得到指定位置下划线的宽度
    private int getLineWidth(int position) {
        if (position < 0 || position >= mTextViews.size())
            return 0;
        int viewWidth = mTextViews.get(position).getWidth();
        return viewWidth - mContentPadding * 2;
    }

    //得到指定位置的偏移量
    private int getOffSet(int position) {
        if (position < 0 || position >= mTextViews.size())
            return 0;
        int offset = 0;
        for (int i = 0; i < position; i++)
            offset += mTextViews.get(i).getWidth();
        return offset + mContentPadding;
    }
}